package cn.flant.io.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class StringMessageHandler extends MessageHandler {
	private DatagramSocket socket;

	@Override
	public void onInit(DatagramSocket socket) throws IOException {
		this.socket = socket;
	}

	@Override
	public Object readMessage(byte[] bytes, int offset, int length) throws IOException {
		return new String(bytes, offset, length, getCharset());
	}

	@Override
	public void sendMessage(InetAddress addr, int port, Object message) throws IOException {
		if (message == null) {
			return;
		}
		byte[] bytes = message.toString().getBytes(getCharset());
		DatagramPacket packet = new DatagramPacket(bytes, bytes.length, addr, port);
		socket.send(packet);
	}

	@Override
	public void onClosed() {
	}
}
